import { Ast, createRootAst } from "./ast";
import { BaseVisitor } from "./core";

class SwitchAccountContext {
    side_account_nickname: string;
    side_account_avatar: Ast;
    current_user: string;
    main_account_nickname: string;
    main_account_avatar: Ast;
}
class SwitchAccountVisitor extends BaseVisitor {
    visitImageView(ast: Ast, ctx: SwitchAccountContext) {
        if (ast.sid === `side_account_avatar`) {
            ctx.side_account_avatar = ast;
            return;
        }
        if (ast.sid === `main_account_avatar`) {
            ctx.main_account_avatar = ast;
            return;
        }
        return ast.children.map(c => c.visit(this, ctx))
    }
    visitTextView(ast: Ast, ctx: SwitchAccountContext) {
        if (ast.sid === `side_account_nickname`) {
            ctx.side_account_nickname = ast.text
            return;
        }
        if (ast.sid === `main_account_nickname`) {
            ctx.main_account_nickname = ast.text;
            return;
        }
        return ast.children.map(c => c.visit(this, ctx))
    }
    visitRelativeLayout(ast: Ast, ctx: SwitchAccountContext) {
        if (ast.sid === `switch_current_user_tip_two_layout`) {
            ctx.current_user = `side`;
            return;
        }
        if (ast.sid === `switch_current_user_tip_layout`) {
            ctx.current_user = `main`;
            return;
        }
        return ast.children.map(c => c.visit(this, ctx))
    }
}

export function switchAccount() {
    const visitor = new SwitchAccountVisitor()
    const ctx = new SwitchAccountContext();
    const root = createRootAst()
    root.visit(visitor, ctx)
    while (!ctx.current_user) {
        const root = createRootAst()
        root.visit(visitor, ctx)
        sleep(1000)
    }
    if (ctx.current_user === 'main') {
        ctx.side_account_avatar.click()
        return ctx.side_account_nickname;
    } else {
        ctx.main_account_avatar.click()
        return ctx.main_account_nickname;
    }
}
